package com.fzrskj.cloud.free.user.service;

import com.fzrskj.cloud.free.consts.CConsts;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.tool.CSessionTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.ConfigPropUtils;
import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.core.utils.ProtectionStartUtils;
import com.fzrskj.cloud.free.sys.bean.Param;
import com.fzrskj.cloud.free.sys.bean.Role;
import com.fzrskj.cloud.free.sys.utils.CDicUtils;
import com.fzrskj.cloud.free.sys.utils.CUserUtils;
import com.fzrskj.cloud.free.sys.utils.SendMailUtils;
import com.fzrskj.cloud.free.sys.utils.SendSMSUtils;
import com.fzrskj.cloud.free.user.utils.UserIssueUtils;
import com.fzrskj.cloud.free.user.bean.UserIssue;
import com.fzrskj.cloud.free.user.bean.UserIssueView;
import com.winiis.component.common.utils.encrypt.Encrypt3DESUtils;
import com.winiis.component.common.utils.tool.CSysTool;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserIssueService extends CObject{
	
	/**
	 * 查询工单列表
	 * @param req
	 * @param resp
	 * @param p={}
	 * @param sid
	 * @return
	 */
	public String queryIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int page = CJsonTool.getIntValue(p, "page", -1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);
		String userName = CSessionTool.getAccountCloud(sid);
		String id = CJsonTool.getStrValue(p,"workId", "");
		String startDate = CJsonTool.getStrValue(p, "startDate", "");
		String endDate = CJsonTool.getStrValue(p, "endDate", "");
		String issueCode = CJsonTool.getStrValue(p, "issueCode", "");
		int state = CJsonTool.getIntValue(p, "state", 0);

		Map<String, Object> cdt = new HashMap<String, Object>();
		if(!CStrTool.isBlankStr(userName)) {
			cdt.put("userName", userName);
		}
		if(!CStrTool.isBlankStr(id)) {
			cdt.put("id", id);
		}
		if(!CStrTool.isBlankStr(startDate)) {
			cdt.put("start", startDate);
		}
		if(!CStrTool.isBlankStr(endDate)) {
			cdt.put("end", endDate);
		}
		if(!CStrTool.isBlankStr(issueCode)) {
			cdt.put("issueCode", issueCode);
		}
		if(state>0) {
			cdt.put("state", state);
		}

		UserIssueUtils userIssueUtils = new UserIssueUtils();
		int count = userIssueUtils.queryIssueCount(cdt);
		int pages= Math.round((count+pagesize-1)/pagesize);
		String code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		List<UserIssueView> queryIssue = userIssueUtils.queryIssue(cdt,page,pagesize);
		code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String data = String.format("{\"queryIssue\":%s}",CJsonTool.listBeanToJson(queryIssue));
		return XmlCodeParser.formatResultPageData(code, page, pages, pagesize, count, data);
	}

	/**
	 * 查询工单列表(管理员)
	 * @param req
	 * @param resp
	 * @param p={}
	 * @param sid
	 * @return
	 */
	public String queryAdminIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int page = CJsonTool.getIntValue(p, "page", -1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);
		String userName = CJsonTool.getStrValue(p,"userName", "");
		String id = CJsonTool.getStrValue(p,"workId", "");
		String startDate = CJsonTool.getStrValue(p, "startDate", "");
		String endDate = CJsonTool.getStrValue(p, "endDate", "");
		String issueCode = CJsonTool.getStrValue(p, "issueCode", "");
		int state = CJsonTool.getIntValue(p, "state", 0);
		String funcs="";

		//获取角色过滤工单
		String roles=CSessionTool.getDataCloud(sid);
		if(!CStrTool.isBlankStr(roles)){
			roles=roles.replace("[", "").replace("]", "");
			JSONObject param = JSONObject.fromObject(roles);
			CUserUtils cuu = new CUserUtils();
			Role role = cuu.getRole(param.getString("id"));
			if(role!=null) {
				funcs = role.getFunctions();
			}
		}

		Map<String, Object> cdt = new HashMap<String, Object>();
		if(!CStrTool.isBlankStr(userName)) {
			cdt.put("userName", userName);
		}
		if(!CStrTool.isBlankStr(id)) {
			cdt.put("id", id);
		}
		if(!CStrTool.isBlankStr(startDate)) {
			cdt.put("start", startDate);
		}
		if(!CStrTool.isBlankStr(endDate)) {
			cdt.put("end", endDate);
		}
		if(state>0) {
			cdt.put("state", state);
		}
		if(!CStrTool.isBlankStr(issueCode)){
			if(!CStrTool.isBlankStr(funcs)){
				if(funcs.indexOf(issueCode)>-1) {
					cdt.put("issueCode", issueCode);
				} else {
					cdt.put("issueCode", "");
				}
			} else {
				cdt.put("issueCode", issueCode);
			}
		} else if (!CStrTool.isBlankStr(funcs)) {
			cdt.put("issueCode", funcs);
		}

		UserIssueUtils userIssueUtils = new UserIssueUtils();
		int count = userIssueUtils.queryIssueCount(cdt);
		String code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		int pages= Math.round((count+pagesize-1)/pagesize);
		List<UserIssueView> queryIssue = userIssueUtils.queryIssue(cdt,page,pagesize);
		code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		return XmlCodeParser.formatResultPageData(code, page, pages, pagesize, count, CJsonTool.listBeanToJson(queryIssue));
	}

	/**
	 * 删除工单
	 * @param req
	 * @param resp
	 * @param p={}
	 * @param sid
	 * @return
	 */
	public String delIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		if(userName == "") {
			userName = CSessionTool.getAccountCloud(sid);
		}
		int id = CJsonTool.getIntValue(p, "id", -1);
		UserIssueUtils userIssueUtils = new UserIssueUtils();
		int ret = userIssueUtils.delIssue(userName, id);
		String code = userIssueUtils.getErrCode();
		return XmlCodeParser.formatResultTips(ret>0,code);
	}

	/**
	 * 查询工单详情
	 * @param req
	 * @param resp
	 * @param p={}
	 * @param sid
	 * @return
	 */
	public String queryIssueDetails(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		int id = CJsonTool.getIntValue(p, "id", -1);
		UserIssueUtils userIssueUtils = new UserIssueUtils();
		UserIssueView queryDetails = userIssueUtils.queryDetailsView(userName, id);
		String code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String mobile = Encrypt3DESUtils.decrypt(queryDetails.getMobile(), ConfigPropUtils.getEncryptKeyService());
		queryDetails.setMobile(ProtectionStartUtils.mobile(mobile));
		String responseString = CJsonTool.beanToJson(queryDetails);
		responseString = JsonTool.addNode(responseString, "mobileAdmin", EncryptUtils.encodeSession(mobile));
		return XmlCodeParser.formatResultData(true, code, responseString);
	}

	/**
	 * 查询工单内容
	 * @param req
	 * @param resp
	 * @param p={"userName":"userName","id":id}
	 * @param sid
	 * @return
	 */
	public String queryContent(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", "");
		int id = CJsonTool.getIntValue(p, "id", -1);
		int page = CJsonTool.getIntValue(p, "page", -1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);
		UserIssueUtils userIssueUtils = new UserIssueUtils();
		List<UserIssue> queryContent = userIssueUtils.queryContent(userName, id,page,pagesize);
		String code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		int count = userIssueUtils.queryCount(userName, id);
		int pages= Math.round((count+pagesize-1)/pagesize);

		//取最后一条记录(如果是管理员回复计算自动关闭时间)
		String time="";
		if(queryContent.size()>0){
			UserIssue ui=queryContent.get(queryContent.size()-1);
			if(ui.getState()==4){
				CDicUtils cUtils=new CDicUtils();
				Param param=cUtils.getParam("workOrderCloseTime");
				if (param != null && !StrTool.isBlankStr(param.getParamValue())) {
					Date date = CDateTimeTool.incHour(ui.getIssueTime(), Integer.parseInt(String.valueOf(param.getParamValue())));
					time = CDateTimeTool.formatDateTime(date, "yyyy-MM-dd HH:00:00");
				}
			}
		}

		String data = String.format("{\"time\":%s,\"list\":%s}","\""+time+"\"",CJsonTool.listBeanToJson(queryContent));
		return XmlCodeParser.formatResultPageData(code, page, pages, pagesize, count, data);
	}

	/**
	 * 回复工单
	 * @param req
	 * @param resp
	 * @param p={"id":id,"userName":"userName","issueDesc":"issueDesc",}
	 * @param sid
	 * @return
	 */
	public String replyIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int id = CJsonTool.getIntValue(p,"id", -1);
		String userName = CJsonTool.getStrValue(p, "userName", "");
		String adminName = CSessionTool.getAccountCloud(sid);
		String issueDesc = CJsonTool.getStrValue(p, "issueDesc", "");
		String attachmentUrl = CJsonTool.getStrValue(p, "attachmentUrl", "");
		int adminId = CSessionTool.getUidCloud(sid);
		int ret=0;

		//获取单个工单
		UserIssueUtils userIssueUtils = new UserIssueUtils();
		UserIssue queryDetails = userIssueUtils.queryDetails(userName, id);
		String code = userIssueUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		queryDetails.setIssueDesc(issueDesc);
		queryDetails.setIssueTime(new Date());
		queryDetails.setParentIssueId(id);
		queryDetails.setAttachmentUrl(attachmentUrl);
		//如果获取到的userName不相等，等于是管理员回复
		if(!userName.equals(adminName)){
			queryDetails.setReplyer(adminName);
			queryDetails.setReplyerId(adminId);
			queryDetails.setState(4);
			ret = userIssueUtils.replyIssue(queryDetails);
			code = userIssueUtils.getErrCode();
			if(ret>0){
				userIssueUtils.updateIssue(id,4);
				if(queryDetails.getNotifyType()==1) {
					SendMailUtils.sendIssueMail(queryDetails); //发送确认邮件
				} else if(queryDetails.getNotifyType()==2) {
					SendSMSUtils.sendIssueSMS(queryDetails);   //发送确认短信
				} else if(queryDetails.getNotifyType()==3) {
					SendMailUtils.sendIssueMail(queryDetails); //发送确认邮件
					SendSMSUtils.sendIssueSMS(queryDetails);   //发送确认短信
				}
			}
		}else{
			UserIssue ui=userIssueUtils.queryLastIssue(queryDetails.getParentIssueId(), CloudContextUtils.getSession().getUID());
			if(ui!=null){
				if(ui.getState()==1 || ui.getState()==2 || ui.getState()==5){
					return XmlCodeParser.formatCustomTips(false, "请等待回复");
				}
			}

			queryDetails.setState(2);
			ret = userIssueUtils.replyIssue(queryDetails);
			code = userIssueUtils.getErrCode();
			if(ret>0){
				userIssueUtils.updateIssue(id,2);
				SendMailUtils.sendIssueToAdminMail(queryDetails);//给管理员发送邮件
			}
		}
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 提交工单
	 * @param req
	 * @param resp
	 * @param p={}
	 * @param sid
	 * @return
	 */
	public String addUserIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();

		String userName = CSessionTool.getAccountCloud(sid);
		int userId = CSessionTool.getUidCloud(sid);
		UserIssue ui = (UserIssue)CJsonTool.jsonToBean(p, UserIssue.class);
		ui.setWorkId("T-"+ CSysTool.GetRndPwd(8));
		ui.setParentIssueId(0);
		ui.setUserName(userName);
		ui.setState(1);
		ui.setUserId(userId);
		ui.setIssueTime(new Date());
		String mobile = EncryptUtils.decodeSession(ui.getMobile());
		ui.setMobile(Encrypt3DESUtils.encrypt(mobile, ConfigPropUtils.getEncryptKeyService()));

		JSONObject result = new JSONObject();
		UserIssueUtils uiUtils = new UserIssueUtils();
		//查询工单类型中是否有未完成工单
		UserIssue entity = uiUtils.queryNoEndUserIssue(ui.getIssueCode(),ui.getIdentName(),uid);
		if(entity!=null){
			result.put("code", "-1");
			result.put("issueCode", ui.getIssueCode());
			result.put("result", "noEndWO");
			return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS,result.toString());
		}
		int ret = uiUtils.replyIssue(ui);
		if(ret>0){
			//给管理员发送邮件
			//发送确认邮件
			SendMailUtils.sendIssueToAdminMail(ui);
		}

		if(ret>0) {
			result.put("code", "0");
		} else {
			result.put("code", "-1");
		}
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS,result.toString());
	}

	/**
	 * 更新工单状态
	 * @param req
	 * @param resp
	 * @param p={"id":id}
	 * @param sid
	 * @return
	 */
	public String uptUserIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int id = CJsonTool.getIntValue(p,"id", -1);
		String opt = CJsonTool.getStrValue(p,"opt", "");
		int state=0;
		if("close".equals(opt)) {
			//关闭工单
			state = 3;
		} else if("processing".equals(opt)) {
			//转正在处理
			state = 5;
		}

		UserIssueUtils userIssueUtils = new UserIssueUtils();
		int ret = userIssueUtils.updateIssue(id,state);
		String code = userIssueUtils.getErrCode();
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 更新工单状态(管理员)
	 * @param req
	 * @param resp
	 * @param p={"id":id}
	 * @param sid
	 * @return
	 */
	public String adminUptIssue(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int id = CJsonTool.getIntValue(p,"id", -1);
		String opt = CJsonTool.getStrValue(p,"opt", "");
		int state=0;
		if("close".equals(opt)) {
			//关闭工单
			state = 3;
		} else if("processing".equals(opt)) {
			//转正在处理
			state = 5;
		}

		UserIssueUtils userIssueUtils = new UserIssueUtils();
		int ret = userIssueUtils.updateIssue(id,state);
		String code = userIssueUtils.getErrCode();
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 统计工单(根据状态)
	 * @param req
	 * @param resp
	 * @param p={}
	 * @param sid
	 * @return
	 */
	public String queryIssueCount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int state = CJsonTool.getIntValue(p, "state", -1);

		if (state <= 0){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		if (state > 0) {map.put("state", state);}

		UserIssueUtils userIssueUtils = new UserIssueUtils();
		int count = userIssueUtils.queryIssueCount(map);
		String code = userIssueUtils.getErrCode();
		userIssueUtils.dispose();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultData(true, code,"\""+count+"\"");
	}

	/**
	 * 删除上传文件
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String delloadwork(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String file = CJsonTool.getStrValue(p, "file", "");
		if(CStrTool.isBlankStr(file)){
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		//判断是不是window
		/*if((System.getProperty ("os.name")).indexOf("Win")>-1 ||(System.getProperty ("os.name")).indexOf("win")>-1){
			file = file.substring(1,file.length());
			int i= file.indexOf("/");
			file = file.substring(i,file.length());
		}*/
		String tempPath = req.getSession().getServletContext().getRealPath(file);
		UserIssueUtils userIssueUtils = new UserIssueUtils();
		boolean flag = userIssueUtils.delloadwork(tempPath);
		userIssueUtils.dispose();
		if(flag){
			return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
		}else{
			return XmlCodeParser.formatResultTips(false, SysErr.FILE_NOT_FOUND);
		}
	}
}